<template>

  <div class="the-list">

    <div class="panel-search">
      <el-form inline :model="listQuery" class="demo-form-inline">

        <el-form-item label="发布状态">
          <el-select v-model="listQuery.status" filterable placeholder="选择状态">
            <el-option label="全部" value="" />
            <el-option label="待发布" :value="0" />
            <el-option label="已发布" :value="1" />
            <el-option label="已下架" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="类目">
          <el-select v-model="listQuery.category" filterable placeholder="选择类目">
            <el-option v-for="(item,index) in typeList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="发布渠道">
          <el-select v-model="listQuery.releaseChannels" filterable multiple placeholder="选择渠道" style="width:480px;">
            <el-option v-for="(item,index) in channelList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="原创/转载">
          <el-select v-model="listQuery.contentSource" filterable placeholder="选择原创/转载">
            <el-option label="全部" value="" />
            <el-option label="原创" :value="1" />
            <el-option label="转载" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker v-model="dateRange.createdTime" type="datetimerange" align="right" unlink-panels :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="发布时间">
          <el-date-picker v-model="dateRange.releaseTime" type="datetimerange" align="right" unlink-panels :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="icon-search" @click="filterHandle">查询</el-button>
          <el-button type="warning" icon="icon-plus" @click="toManage('create')">发布内容</el-button>
        </el-form-item>

      </el-form>
    </div>

    <div class="panel-table">
      <div class="table-head">
        <span>数据列表</span>
      </div>
      <el-table :data="list" stripe :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" style="width: 100%;" border>

        <el-table-column label="内容编号" prop="id" />

        <el-table-column label="类目" prop="releaseChannel">
          <template #default="{row}">
            {{getArrayItem("typeList","id",row.category).name}}
          </template>
        </el-table-column>

        <el-table-column label="原创/转载" prop="contentSource">
          <template #default="{row}">
            {{row.contentSource == 1 ? '原创' : '转载'}}
          </template>
        </el-table-column>

        <el-table-column label="标题" prop="title" />

        <el-table-column label="创建时间" prop="createdAt" />

        <el-table-column label="发布时间" prop="releaseTime" />

        <!-- <el-table-column label="趣摸鱼权重" prop="sortQmy">
          <template #default="{row}">
            <el-input v-if="row.releaseChannel===1 || row.releaseChannel===3" v-model="row.sortQmy" size="small" :min="0" @change="changeSortOrWatchnum(row,'sortQmy')" style="max-width:80px;"></el-input>
            <p style="text-align:center;" v-else>-</p>
          </template>
        </el-table-column>

        <el-table-column label="供销端权重" prop="sortGxd">
          <template #default="{row}">
            <el-input v-if="row.releaseChannel===2 || row.releaseChannel===3" v-model="row.sortGxd" size="small" :min="0" @change="changeSortOrWatchnum(row,'sortGxd')" style="max-width:80px;"></el-input>
            <p style="text-align:center;" v-else>-</p>
          </template>
        </el-table-column> -->

        <el-table-column label="浏览量" prop="watchNum">
          <template #default="{row}">
            <el-input v-model="row.watchNum" size="small" :min="0" @change="changeSortOrWatchnum(row,'watchNum')" style="max-width:80px;"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="状态" prop="status">
          <template #default="{row}">
            {{row.status == 0 ? '待发布' : row.status == 1 ? '已发布' : '已下架'}}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="220px">
          <template #default="{row}">
            <template v-if="row.status == 0 || row.status == 1">
              <el-button type="warning" size="small" @click.stop="lowerUpperMarket(row)">下架
              </el-button>
              <el-button type="primary" size="small" @click.stop="toManage('detail',row.id)">查看
              </el-button>
              <!-- <el-button type="primary" size="small" @click="openShareBox(row)">分享
              </el-button> -->
            </template>
            <template v-else-if="row.status == 2">
              <el-button type="danger" size="small" @click.stop="deleteBlogstore(row.id)">删除</el-button>
              <el-button type="success" size="small" @click.stop="toManage('edit',row.id)">编辑
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-pagination">
        <pagination :total="total" v-model:page="listQuery.page" v-model:limit="listQuery.pageSize" @pagination="getTableList" />
      </div>

    </div>

  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { ElMessageBox } from "element-plus";
import {
  getBlogstoreList,
  deleteBlogstoreOne,
  changeBlogstoreOneStatus,
  editBlogstoreSortOrWatchnum,
} from "@/api/blogstore";
import { ElMessage } from "element-plus";
export default {
  name: "blogstoreList",
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (
        from.path.indexOf("/blogstore/edit") >= 0 ||
        from.path.indexOf("/blogstore/create") >= 0
      ) {
        vm.getTableList();
      }
    });
  },
  data() {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      listQuery: {
        category: "",
        // releaseChannels: [0, 1, 2, 3],
        contentSource: "",
        status: "",
        createdStated: "", //创建时间
        createdEnd: "",
        releaseStated: "", //发布时间
        releaseEnd: "",
        page: 1,
        pageSize: 10,
      },
      dateRange: {
        createdTime: "",
        releaseTime: "",
      },
      dateCreateRange: [],
      listLoading: false,
      list: [],
      total: 0,
      shareOPT: {
        showBox: false,
        data: {},
      },
      channelList: [
        // {name: "全部", id: ""},
        { name: "趣摸鱼平台资讯", id: 1 },
        { name: "无发布渠道", id: 0 },
      ],
      typeList: [
        { name: "全部", id: "" },
        { name: "新闻", id: 1 },
        { name: "资讯", id: 2 },
        { name: "广告", id: 3 },
        { name: "系统", id: 4 },
        { name: "其他", id: 5 },
      ],
    };
  },
  components: {
    Pagination,
  },
  mounted() {
    this.getTableList();
  },
  methods: {
    getTableList() {
      this.listLoading = true;

      let dealDate = (dateArr) => {
        return dateArr && dateArr.length === 2 ? dateArr : ["", ""];
      };
      let createdTime = dealDate(this.dateRange.createdTime);
      let releaseTime = dealDate(this.dateRange.releaseTime);
      let req = {
        ...this.listQuery,
        // releaseChannels: (() => {
        //   let len = (this.listQuery.releaseChannels || []).length;
        //   return len === 4 ? "" : this.listQuery.releaseChannels.join(",");
        // })(),
        createdStated: createdTime[0], //创建时间
        createdEnd: createdTime[1],
        releaseStated: releaseTime[0], //发布时间
        releaseEnd: releaseTime[1],
      };
      console.log("req:", req);
      getBlogstoreList(req).then(({ code, data }) => {
        console.log("res:", data);
        if (code === 0) {
          this.list = data.items;
          this.total = data.pagination.total_record;
          this.listLoading = false;
        } else {
          this.listLoading = false;
        }
      });
    },
    filterHandle() {
      this.listQuery.page = 1;
      this.getTableList();
    },
    deleteBlogstore(id) {
      ElMessageBox.confirm("是否确认删除该内容?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteBlogstoreOne({ id }).then((res) => {
          if (res.code === 0) {
            // 更新列表
            this.listQuery.page = 1;
            this.getTableList();
          }
        });
      });
    },
    lowerUpperMarket(item) {
      ElMessageBox.confirm("是否确认下架该内容?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        changeBlogstoreOneStatus({
          id: item.id,
          status: 2, // 状态2为下架
        }).then((res) => {
          if (res.code === 0) {
            // 更新列表
            // this.listQuery.page = 1;
            this.getTableList();
          }
        });
      });
    },
    changeSortOrWatchnum(row, type) {
      let { value, pass } = this.checkNumber(row[type]);
      row[type] = value;
      if (!pass) {
        return;
      }
      let req = {
        id: row.id,
        [type]: value,
      };
      console.log("row:", type, row);
      editBlogstoreSortOrWatchnum(req).then((res) => {
        if (res.code === 0) {
          ElMessage.success(
            {
              watchNum: "修改浏览量成功！",
              sortQmy: "修改权重值成功！",
              sortGxd: "修改权重值成功！",
            }[type]
          );
        }
      });
    },
    checkNumber(num) {
      console.log("num:", num);
      let num2 = parseInt(num);
      if (isNaN(num2) || num2 < 0) {
        return { value: 0, pass: false };
      } else {
        return { value: num2, pass: true };
      }
    },
    toManage(type, id) {
      if (type === "edit") {
        this.$router.push(`/blogstore/edit/${id}`);
      } else if (type === "detail") {
        this.$router.push(`/blogstore/detail/${id}`);
      } else if (type === "create") {
        this.$router.push(`/blogstore/create`);
      }
    },

    openShareBox(info) {
      this.shareOPT.showBox = true;
      this.shareOPT.data = info || {};
    },
    closeShareBox() {
      this.shareOPT.showBox = false;
      this.shareOPT.data = {};
    },
    copyLink(id, type) {
      if (type === "QMY") {
        return (
          import.meta.env.VITE_APP_URL_HOST + "/activity/newDetail?id=" + id
        ); // '&ed=GXD'
      } else {
        return import.meta.env.VITE_APP_URL_HOST_GXD + "/news/details?id=" + id; // '&ed=QMY'
      }
    },
    clipboardSuccess() {
      ElMessage({
        message: "复制成功",
        type: "success",
      });
    },

    // 获取数组某一项
    getArrayItem(listName, key, value) {
      let list = this[listName] || [];
      for (let prop of list) {
        if (prop[key] === value) {
          return prop;
        }
      }
      return {};
    },
  },
};
</script>


<style scoped lang="scss">
@import "@/styles/tablePage.scss";
.the-list{
  height: 100%;
}
.el-form-item {
  margin-bottom: 8px;
}
</style>

